(function($) {

	//addon products validation
	KOR.Validator.AddOnProductForm = {
		errorMessagePosition: 'before',
		formValid: function(){
			return false
		}
	};

	//product validation
	KOR.Validator.ProductForm = {
		errorClass: 'kor-field-error-message',
		errorMessagePosition: 'placeholder',
		postFailureFieldEvents: 'blur',
		formValid: function(form, silent){
			var success = true;
			if(form.closest('[data-bus]').attr('data-addon') || form.closest('[data-product]').attr('data-addon')){
				return false;
			}else{
				//handle hidden field for warranties
				$('input[type=hidden][name^=DependentSKU_][class=kor-warranty]', form).remove();
				$('input.kor-product-warranty["type=radio"]:checked').each(function(){
					var name = $(this).attr('name'),
						value = $(this).val();
					form.append('<input class="kor-warranty" type="hidden" name="{{0}}" value="{{1}}" />'.uInject(name,value));
				});
				//handle hidden fields for addon products
				$('input[type=hidden][name=SKU][class=kor-addon], input[type=hidden][name^=Quantity_][class=kor-addon]', form).remove();
				var addOnSkus = [];
				$('[data-addon=true][data-product], [data-addon=true] [data-product]').each(function(){
					var product = $(this),
						addonform = $('form.kor-product', product),
						quantityField = $('input[name^=Quantity_]', addonform).trigger('blur'),
						sku = $('input[name=SKU]', addonform).val(),
						validator = addonform.data('validator-instance'),
						quantity = quantityField.length ? quantityField.val() : product.attr('data-min-quantity');
					if (!validator) {
						addonform.focus();
						validator = addonform.data('validator-instance');
					}

					if(validator && !addonform.data('skipping')){
						addonform.trigger('submit', [silent]);
						if(addonform.attr('data-valid')){
							if (sku && quantity > 0) {
								addOnSkus.push('<input class="kor-addon" type="hidden" name="SKU" value="{{0}}" /><input class="kor-addon" type="hidden" name="Quantity_{{0}}" value="{{1}}" />'.uInject(sku, quantity));
							}
						}
						else {
							success = false;
						}
					}
				});
				if(addOnSkus.length){
					form.append(addOnSkus.join(''));
				}
			}
			return success;
		}
	};

	KOR.namespace('KOR').ObjectFactory = {

		getProduct: function(uri, callback){
			var productJSON = KOR.namespace('KOR.product.productJSON');
			if(productJSON[uri]){
				callback(productJSON[uri]);
			} else {
				$.get('{{}}&ProductUUID={{}}'.uInject(KOR.store.urls.productJSON, uri), function(json){
					json = KOR.decodeJSON(json);
					productJSON[json.productUUID] = json;
					callback(json);
				});
			}
		},

		getStatesList: function(callback){
			callback($.map($('#state-values option:not([value=""])'), function(opt){
				return  $(opt).html() + " - " + $(opt).val()
			}))
		},

		getExtString: function(){
			var args = $.makeArray(arguments);
			var uri = args.shift();
			var callback = args.pop();
			var extString = KOR.extStrings.strings.fieldFailureMessageDefault;
			if(KOR.extStrings.strings[uri]){
				extString = KOR.extStrings.strings[uri]
			}
			callback(extString.uInject(
				args.length == 1 && $.type(args[0]) == 'array' ? args[0] : args)
			);
		},

		getExtStringBabushka: function(){
			var args = $.makeArray(arguments);
			var uri = args.shift();
			var callback = args.pop();
			var extString = KOR.extStrings.strings[uri] || KOR.extStrings.strings.fieldFailureMessageDefault;

            $.each(args, function(i,v){
                extString = extString.uInject(
                    KOR.extStrings.strings[v] ? KOR.extStrings.strings[v] : v
                )
            });

			callback(extString);
		},

		getTemplate: function(id, callback){
			callback(KOR.templates[id]);
		}
	}

	KOR.Captcha = {
		render: function(element, library){
			this['render' + (library || this.library)](element)
		}
	}
	$.extend(KOR.Captcha, {
		library: 'ReCaptcha',

		renderReCaptcha: function(element){
			var id = element.attr('id');
			if (!id){
				id = "kor-".uId();
				element.attr('id', id);
			}
			Recaptcha.create(this.reCaptchaKey, id, this.reCaptchaOptions || {});
		}
	});

	$.fn.captcha = function(){
		$(this).each(function(){
			KOR.Captcha.render($(this));
		});
	}

	$.fn.refreshCartInHeader = function(){
		var minicartSummary = $('.kor-minicart-group')
		$.ajax({
			url: $('.kor-minicart-group').attr('data-pagelet-url'),
			context: document.body,
			success: function(html){
				minicartSummary.replaceWith(html)
			}
		});

	}
	/**
	 * Adds the ability to reverse a jQuery Array of objects
	 **/
	$.fn.reverseObject = [].reverse;

	KOR.behaviors = KOR.behaviors || {}
	$.extend(KOR.behaviors, {
		setAjaxLoader: function() {
			var clientX, clientY, ajaxCalls = 0;

			/**
			 * Register Global AJAX wait indicator
			 **/
			$(document).ajaxSend(function() {
				$('.ws-small-loader').show().css({
					left: clientX + 5 + $(document).scrollLeft(),
					top: clientY + 5 + $(document).scrollTop()
				})
				ajaxCalls++
			})

			$(document).bind('mousemove', function(ev) {
				clientX = ev.clientX;
				clientY = ev.clientY
				if (ajaxCalls) {
					$('.ws-small-loader').css({
						left: ev.clientX + 5 + $(document).scrollLeft(),
						top: ev.clientY + 5 + $(document).scrollTop()
					})
				}
			})
			/**
			 * Register Global AJAX wait indicator
			 **/
			$(document).ajaxComplete(function(ev) {
				$('.ws-small-loader').hide()
				ajaxCalls--
			})
		},
		setAjaxFormsAction: function(){
			$(document).delegate('[data-ajax-url]', 'mouseover', function(ev){
				var target = $(ev.currentTarget);
				if(!target.data('form-ajax-override-set')){
					target.attr('action', target.attr('data-ajax-url'));
					target.data('form-ajax-override-set', true);
				}
			})
		},
		setCountryDropdown: function(){
			/**
			 * Loads required address fields based on country selection
			 **/
			$(document).delegate('.kor-form select.kor-country-list', 'change keyup', function(ev) {
				if (ev.keyCode == 13 || ev.keyCode == 0 || ev.keyCode == undefined) {
					var target = $(ev.currentTarget)
		
					var formType=target.attr('name').split('_')[0] || 'billing';
					var tabIndex= target.attr('tabindex')-1 || 5;
					var addresscontainer = target.closest('.ws-form')
					var form = addresscontainer.closest('form')
					var params = form.serialize() +'&formType='+formType+'&tabIndex='+tabIndex
					$('input', form).attr('disabled', true)
					$.post($(this).attr('data-url'), params, function(data){
						addresscontainer.fadeOut('slow', function() {
							addresscontainer.replaceWith(data);
							$('input', form).attr('disabled', false)
							addresscontainer.fadeIn('slow');
						});
					});
				}
			});
		},

		setZoomRotate: function(){
			/**
			 * Initialize zoom/rotate images
			 */
			var zoomRotateSelector = '.kor-zoom-rotate[data-zoom-behavior=inlinezoom]',
				sliderSelector = '.kor-range-slider',
				zoomButtonSelector = '.kor-zoom-button',
				zoomIDArgument = 'data-zoom-rotate-id';

			KOR.inlineZoom(zoomRotateSelector);

			function setZoomRotateEvent(origin, eventType, target, targetName, action) {
				$(document).delegate('{{}}[{{}}]'.uInject(origin, zoomIDArgument), eventType, function(ev, data){
					KOR.verbose('HANDLE: ' + eventType, ev, data);
					var prodId = $(this).attr(zoomIDArgument);
					if (prodId) {
						$(document).find('{{}}[{{}}={{}}]'.uInject(target, zoomIDArgument, prodId)).each(function (idx, elem) {
							var targetData = '{{}}-instance'.uInject(targetName),
								inst = $(elem).data(targetData) || $(elem).focus().data(targetData);
							if (inst) action.apply(inst, [ev, data, elem]);
						});
					}
				});
			}

			setZoomRotateEvent(zoomButtonSelector, 'zoomButton:toggle', zoomRotateSelector, 'inlineZoom', function(ev, data, node) {
				this.zoomToggle();
			});
			/**
			 * Initialize zoom-rotate zoom button and rotate slider
			 */
			KOR.zoomButton(zoomButtonSelector);
			KOR.rangeSlider(sliderSelector);
			$(document).delegate(sliderSelector, 'rangeSlider:change', function(ev, data) {
				obj = $(this);
				obj.getBusInstance().getDomainModel({
					node: obj.closest('[data-product]'),
					callback: function(domEventObj) {
						this.handleRotateControl({target:domEventObj.model, message:data});
					}
				});
			});
		},
		rangeSliderChangeHandler: function(ev, data){
			obj = $(this);
			obj.getBusInstance().getDomainModel({
				node: obj.closest('[data-product]'),
				callback: function(domEventObj) {
					this.handleRotateControl({target:domEventObj.model, message:data});
				}
			});
		},

		dialogPopulateHandler: function(data, instance){
			$('.kor-captcha-content').captcha();
			$('.ws-expressshop-cart-title').refreshCartInHeader();
			if (typeof sr_$ !== 'undefined') {
				sr_$.actions.refresh_page();
			}
		},

		/**
		 * Submits the hijacked form via ajax
		 **/
		formHijaxHandler: function(ev){
			var target = $(ev.target).closest('form[data-valid=true]');
			if(target.length){
				ev.preventDefault();
				var params = target.serialize() //+ "&" + ev.currentTarget.name + "=" + $(ev.currentTarget).val();
				$.post(target.attr('action'), params, function(html){
					var overlay = target.closest('.kor-overlay')
					overlay.trigger(overlay.attr('data-comp-type') + ':populate', html)
				});
			}
		},
		/**
		 * Hijacks links inside a dialog inorder to open the content within the dialog itself
		 **/
		dialogHijaxHandler: function(ev){
			ev.preventDefault();
			var target = $(ev.target);
			$.get(target.attr('href'), function(html){
				target.closest('.kor-overlay').trigger('dialog:populate', html)
			});
		},
		setAccountSection: function(){
			/* add new address show */
			$(document).delegate('.ws-add-address', 'click', function(ev){
				$('.ws-add-address').fadeOut()
				$('.ws-add-new-address').slideDown('slow', function(){
					$(this).css('display', 'block')
				})
				return false;
			})
			
			/* add new address hide */
			$(document).delegate('.ws-add-new-address .ws-cancel', 'click', function(ev){
				$('.ws-add-address').fadeIn();
				$('.ws-add-new-address').slideUp();
				return false;
			})
		},
		setSearchBehaviors: function() {
			/**
			 * Toggles helper text in the search field
			 * Removes helper text when field is moused over or focused
			 * focus: Adds focused to the search field so helper text doesn't reappear when mousing out of the focused search field
			 **/
			$(document).delegate('.ws-search-input', 'mouseover focus', function(ev){
				var el = $(ev.currentTarget)

				if(el.attr('data-default-value') == el.val()){
					el.val('')
					el.removeClass('ws-search-input-off')
				}
				if(ev.type == 'focusin')
					el.data('focused', true);
			})

			/**
			 * If search field isn't focused and no search terms have been typed at mouseout or blur this will put the helper text back in it
			 * blur: Removes focused from the search field
			 **/
			$(document).delegate('.ws-search-input', 'mouseout blur', function(ev){
				var el = $(ev.currentTarget)

				if(ev.type == 'focusout')
					el.data('focused', false);

				if(el.val() == '' && !el.data('focused')){
					el.val(el.attr('data-default-value'))
					el.addClass('ws-search-input-off')
				}
			})

			$(document).delegate('.ws-header-search .ws-go', 'click', function(ev){
				var searchbox = $('.ws-search-input', $(ev.target).closest('form'))
				if(searchbox.val() == searchbox.attr('data-default-value')) {
					searchbox.val('')
				}
			})
		},

		setPromoBehaviors: function() {
			/**
			 * Show Promo entry
			 **/
			$(document).delegate('.ws-promo-code label, .ws-promo-code h1', 'click', function(ev){
				$('.ws-hide', '.ws-promo-code-contents').removeClass('ws-hide').show()
			})

			/**
			 * Enable/Disable Promo Code Submit button
			 **/
			$(document).delegate('.ws-promotion-code-input', 'keyup', function(ev){
				if($(ev.currentTarget).val() != ''){
					$('.ws-apply-promotion').removeClass('ws-disabled').removeAttr('disabled')
				}else{
					$('.ws-apply-promotion').addClass('ws-disabled').attr('disabled', 'disabled')
				}
			})
		},

		setCCfieldBehaviors: function(){
			/**
			 * Credit Card formatting and match test
			 **/
			$(document).delegate('.ws-credit-card-form .kor-ccnum', 'keyup', function(e){
				var ccnum = $(e.target).val().replace(/[^\d]/g, '')
				$('.ws-credit-card-form .ws-credit-type').removeAttr('disabled')
				if (ccnum.match(/^4[0-9]{12}(?:[0-9]{3})?$/)) {
					selectCreditCard('Visa', 'vsa')
				} else if (ccnum.match(/^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/)) {
					// Mastercard: length 16, prefix 51-55, dashes optional.
					selectCreditCard('MasterCard', 'mas')
				} else if (ccnum.match(/^6011-?\d{4}-?\d{4}-?\d{4}$/)) {
					// Discover: length 16, prefix 6011, dashes optional.
					selectCreditCard('Discover', 'dcv')
				} else if (ccnum.match(/^3[4,7]\d{13}$/)) {
					// American Express: length 15, prefix 34 or 37.
					selectCreditCard('Amex', 'amx')
				} else if (ccnum.match(/^3[0,6,8]\d{12}$/)) {
					// Diners: length 14, prefix 30, 36, or 38.
					selectCreditCard('Diners', 'dn')
				}else if (ccnum.match(/(^(5[0678])\d{11,18}$)(^(6[^05])\d{11,18}$)(^(601)[^1]\d{9,16}$)(^(6011)\d{9,11}$)(^(6011)\d{13,16}$)(^(65)\d{11,13}$)(^(65)\d{15,18}$)(^(49030)[2-9](\d{10}$\d{12,13}$))(^(49033)[5-9](\d{10}$\d{12,13}$))(^(49110)[1-2](\d{10}$\d{12,13}$))(^(49117)[4-9](\d{10}$\d{12,13}$))(^(49118)[0-2](\d{10}$\d{12,13}$))(^(4936)(\d{12}$\d{14,15}$))/)){
					selectCreditCard('Maestro', 'mae')
				}else{
					$('.ws-available-cards li').removeClass('ws-inactive')
				}
			})

			$(document).delegate('form.ws-paymentForm', 'submit', function(ev){
				$('.ws-credit-card-form .ws-credit-type').removeAttr('disabled')
			})

			/**
			 * Highlights credit card type based on cardnumber entered
			 */
			function selectCreditCard(type, id){
				var ccSelectBox = $('.ws-credit-card-form .ws-credit-type');
				$('.ws-available-cards li:not([class^=ws-'+id+'])').addClass('ws-inactive')
				ccSelectBox.val(id).attr('disabled', 'disabled')
				$('<input name="'+ ccSelectBox.attr('name') +'" />]','.ws-credit-card-form').attr('value', ccSelectBox.val())
			}

			/**
			 * Mask input of credit cards
			 */
			KOR.mask('.kor-ccnum')
			$(document).delegate('.ws-product-quantity-input', 'keypress', function(ev){
				var key = ev.which;
				var ignore = (key < 16 || (key > 16 && key < 32) || ev.ctrlKey || ev.altKey || ev.metaKey);
				if( ignore || String.fromCharCode( key ).match(/[0-9]/)){
					return true;
				}
				return false;
			})
		},
		setCCWalletBehaviors: function(){
			/**
			 * Edit links
			 */
			$(document).delegate('.kor-edit-credit-card-link', 'click', function(e)
			{
				$(".kor-edit-credit-card-section").slideUp();
				$(this).parents(".ws-payment-wallet-list-item").children(".kor-edit-credit-card-section").slideDown();
				return false;
			})

			/**
			 * hide wallet link
			 */
			$(document).delegate('.ws-wallet-hide-button', 'click', function(e)
			{
				$(this).parents("li.ws-method").contents().find("input[name=PaymentServiceSelection]:not(:checked)").parents("li.ws-payment-wallet-list-item").slideUp();
				$(this).siblings(".ws-wallet-show-button").show();
				$(this).hide();
				return false;
			})

			/**
			 * show wallet link
			 */
			$(document).delegate('.ws-wallet-show-button', 'click', function(e)
			{
				$(this).parents("li.ws-method").contents().find("li.ws-payment-wallet-list-item").slideDown();
				$(this).siblings(".ws-wallet-hide-button").show();
				$(this).hide();
				return false;
			})

			/**
			 * remove security code box before edit cc date
			 */
			$(document).delegate('.editCC', 'click', function(e)
			{
				$('.ws-security-code-field').remove();
				$('.ws-credit-card-form').remove();
			})
		},
		setTips: function(){
			/**
			 * init for the tooltips. They should look like this:
			 *	<a class="tooltip" href="">details</a>
			 *	<span class="tooltip-content">
			 *		<span class="tooltip-wrapper">content</span>
			 *	</span>
			 **/
			KOR.tip('a.ws-tooltip',{
				content: function(event){
					var content = $(event.target).next('.ws-tooltip-content').html()
					return content==null?' ':content;
				}
			})
		},
		setTipMenus: function(){
			/**
			 * context menu / tooltip
			 **/
			KOR.tipMenu('.kor-open-as-tooltip');
			KOR.tipMenu('.kor-open-as-context-menu',{
               content: function(event){
                   var content = $(event.target).next('.ws-tooltip-content').html()
                   return content==null?' ':content;
               }
           })
		},
		setArrowTips: function(){

		},
		setOverlays: function(){
			$(document).delegate(".kor-overlay .ws-close", "click", function(ev){
				$('.kor-control-close',$(ev.target).closest('.kor-overlay')).click()
			})

			/**
			 * Opens a modal/dialog using a template with an iframe
			 **/

			KOR.dialog('.kor-open-as-iframe-dialog', {
				singletonModal: false,
				singletonOverlay: false,
				fixedPosition: false,
				overlayHeaderClass: 'kor-header',
				overlayContentClass: 'kor-content-active',
				overlayTemplate: 'dialogOverlayTemplateWithIframe',
				populate: function(ev){
					this.populateOverlay('', ev)
				},
				populateOverlay: function(html, ev){
					var obj = this;
					KOR.ObjectFactory.getTemplate(this.overlayTemplate, function(str){
						obj.iframeURL = ev.currentTarget.href;
						obj.iframeHeight = $(ev.currentTarget).attr('data-iframe-height');
						obj.iframeWidth = $(ev.currentTarget).attr('data-iframe-width');
						obj.getOverlay(ev).html($(str.uTemplate(obj)).html());
						obj.html = null;
						obj.iframeURL = null;
						obj.iframeHeight = null;
						obj.iframeWidth = null;
						obj.position(ev);
						if(html && obj.onPopulate) obj.onPopulate(html, obj);
					});
				},
				onPopulate: KOR.behaviors.dialogPopulateHandler
			});

			/**
			 * Opens a modal/dialog
			 **/
			KOR.dialog('.kor-open-as-dialog', {
				singletonModal: false,
				singletonOverlay: false,
				fixedPosition: false,
				overlayHeaderClass: 'kor-header',
				overlayContentClass: 'kor-content-active',
				overlayTemplate: 'dialogOverlayTemplate',
				onPopulate: KOR.behaviors.dialogPopulateHandler
			});
		},
		setMiniCart: function(){

			KOR.tipMenu('.kor-minicart-items', {
				overlayTemplate: 'minicartOverlayTemplate',
				anchorPosition: 'right top',
				hideDelay: 1000,
				menu: true,
				overlayOffset: '0 15px',
				overlayPosition: 'right top',
				fixedPosition: false,
				singletonOverlay:false,
				show: function(node, ev){
					$(this.selector).addClass('kor-active-anchor')
					node.slideDown(300)
				},

				hide: function(node, ev){
					$(this.selector).removeClass('kor-active-anchor')
					node.slideUp(300, function(){
						node.html('')
					});
				}
			});
			/* minicart show for a certain time period*/

			var minicart_tid = null;
			$(document).delegate('.ws-minicart-dropdown', 'mouseenter', function(){
				if(minicart_tid) {
					clearTimeout(minicart_tid);
				}
			});

			/* now you can trigger the minicart from everywhere */
			KOR.namespace('KOR.store.minicart').show = function(time){
				var mcl = $('.kor-minicart-items');
				mcl.trigger('tip:show');
				if(time){
					minicart_tid = setTimeout(function(){
						mcl.trigger('tip:hide');
					}, time);
				}
			}

			KOR.store.minicart.hide = function(){
				var mcl = $('.kor-minicart-items');
				mcl.trigger('tip:hide');
			}
		},
		setTogglers: function(){
			KOR.toggler('.kor-toggle');
		},
		setValidators: function(){
			KOR.validator('form:not(.kor-product)', {instantFlashErrors: true, errorMessagePosition: 'placeholder', errorClass: 'kor-field-error-message'});
		},
		setAccordions: function(){
			KOR.accordion('.kor-accordion');
		},
		setTabsets: function(){
			KOR.tabset(".kor-tabset");

			KOR.anchoredTabset('.kor-collection-link-list',{
				activeLabelClass: "kor-collection-link-list-navigation-item-active",
				activeContentClass: "kor-anchored-tabset-content-active",
				labelSelector: ".ws-collection-link-list-navigation .kor-collection-link-list-navigation-item",
				contentSelector: ".kor-anchored-tabset-content",
				autoSizeToContent: false
			})
		},
		setCarousels: function(){
			KOR.carousel('.kor-carousel')
		},
		setFlyoutZoom: function(){
			KOR.flyoutZoom('.kor-zoom-rotate[data-zoom-behavior=flyout]')
		},
		setDropNavs: function(){
			/* init drop down navigation bar*/
			KOR.dropnav('.kor-dropnav', {
				itemChildren: 'div'
			});
		},
		setSuggest: function(){
			/**
			 * Enable ajax search suggest
			 **/
			KOR.suggest('.ws-search-input',{paramName:'SearchTerm',
				showResult: function(value, data) {
					if(data != null && data.length > 0) {
						return data[0];
					} else {
						return value;
					}
				},
				onItemSelect: function(value, obj){
					obj.dom.$elem.closest('form').submit()
				}
			});
			/* Autosuggest for State input */
			KOR.suggest('input#AddressForm_State',{data:KOR.ObjectFactory.getStatesList, matchInside: false,
				displayValue: function(value, data){
					return value.split(' - ')[1]
				}
			});
		},
		setProductView: function() {
			//Validation skipping
			$(document).delegate('[data-product][data-skippable=true] .kor-product-qty', 'keyup blur mouseup change', function(ev) {
				var qtyField = $(ev.target),
					form = qtyField.closest('form'),
					validator = form.data('validator-instance');
				if (!qtyField.val() || qtyField.val() == '0') {
					ev.stopPropagation();
					form.data('skipping', true);
					if (validator) {
						var fields = validator.getFields();
						$.each(fields, function(idx, field) {
							var validators = validator.getValidatorsForField(field);
							$.each(validators, function(qdx, nodeValidator) {
								nodeValidator.success();
							});
						});
					}
				}
				else {
					form.data('skipping', false);
				}
			});

			/**
			 * Observer for addon products on/off toggle
			 **/
			$(document).delegate('.kor-addon-product-toggle', 'click', function(ev){
				ev.preventDefault();
				var target = $(ev.target),
					prodParent = target.closest('[data-product]'),
					prodId = prodParent.attr('data-product'),
					min = KOR.product.productJSON[prodId].minOrderQuantity;
				if (!target.data('toggle')) target.data('toggle', true);
				else target.data('toggle', false);
				$('input[name^=Quantity_]', prodParent).val(
					target.data('toggle') ? (min || 1) : 0);
			});

			/**
			 * Product form validator for addon products
			 **/
			KOR.validator("[data-addon=true]form.kor-product, [data-addon=true] form.kor-product", KOR.Validator.AddOnProductForm);

			/**
			 * Product form validator for main products
			 **/
			KOR.validator("form.kor-product", KOR.Validator.ProductForm);

			KOR.ProductView.registerDomEvents();
		},
		setAddressBookBehaviors: function() {
			/**
			 * Show the add new address form
			 * Hide the add new address link
			 **/
			$(document).delegate('.kor-add-new-address-link', 'click', function(ev) {
				var target = $(ev.currentTarget)
				var slider
				var other
				if( target.hasClass('kor-add-new-billing-address-link')){
					slider = $('.kor-add-new-billing-address');
					other = $('.kor-add-new-shipping-address');
				}else{
					slider = $('.kor-add-new-shipping-address');
					other = $('.kor-add-new-billing-address');
				}
				if(other.is(':visible')) {
					other.find('.ws-cancel').click();
				}
				slider.fadeIn();
				target.closest('.ws-address-selection').fadeOut();
				return false;
			});

			/**
			 * Show the add new address form
			 * Hide the add new address link
			 **/
			$(document).delegate('.kor-edit-address-link', 'click', function(ev) {
				var target = $(ev.currentTarget)
				var slider
				var other
				if( target.hasClass('kor-edit-billing-address-link')){
					slider = $('.kor-edit-billing-address');
					other = $('.kor-edit-shipping-address');
				}else{
					slider = $('.kor-edit-shipping-address');
					other = $('.kor-edit-billing-address');
				}
				if(other.is(':visible')) {
					other.find('.ws-cancel').click();
				}
				slider.fadeIn();
				target.closest('.ws-address-selection').fadeOut();
				return false;
			});

			/**
			 * Hide the add new address form
			 * Show the add new address link
			 **/
			$(document).delegate('.ws-checkout .ws-add-new-address button[type="reset"], .ws-checkout .ws-edit-address button[type="reset"]', 'click', function(ev) {
				var target = $(ev.currentTarget).closest('tr')
				target.fadeOut();
				target.siblings('.ws-address-selection').fadeIn();
			});

			/**
			 * Show the delete address confirmation
			 **/
			$(document).delegate('.kor-remove-address-link', 'click', function(ev){
				$(this).hide()
				$(this).closest('.ws-current-address').find('.kor-shipping-address-remove-confirmation').slideDown()
				return false;
			})

			/**
			 * Hide the delete address confirmation
			 **/
			$(document).delegate('.kor-remove-address-cancellation','click', function(ev){
				$(this).closest('.kor-shipping-address-remove-confirmation').slideUp(function(){
					$(this).closest('.ws-current-address').find('.kor-remove-address-link').show()
				})
				return false;
			})
		},
		setOrderHistory: function(){
			/**
			* Show/Hide confiration frame for order cancellation
			**/
		   $(document).delegate('.ws-cancel-order-confirmation', 'click', function(ev){
			   ev.preventDefault();
			   $('.ws-cancellation-frame').show();
			   
		   });	
			   
		   $(document).delegate('.ws-hide-cancel-confirmation', 'click', function(ev){
			   ev.preventDefault();
			   //alert('cancel!!!');
			   $('.ws-cancellation-frame').hide();
			   
		   });
		   /**
			* Show/Hide Order List
			*/
		   $(document).delegate('.kor-table-show-more-rows-link', 'click', function(ev){
			   ev.preventDefault();
			   $('.ws-hide', $(ev.currentTarget).closest('table')).fadeIn()
			   $('.kor-table-hide-rows-link').show();
			   $('.kor-table-show-more-rows-link').hide();
		   });
		   
		   $(document).delegate('.kor-table-hide-rows-link', 'click', function(ev){
			   ev.preventDefault();
			   $('.ws-hide', $(ev.currentTarget).closest('table')).fadeOut();
			   $('.kor-table-hide-rows-link').hide();
			   $('.kor-table-show-more-rows-link').show();
		   });
		}
	})
})(jQuery);
